package com.xgh.offer;

import com.xgh.ListNode;

/**
 * @ClassName Offer24
 * @Description
 * @Author xinggh
 * @Date 2020/6/30 22:50
 * @Version 1.0
 **/
public class Offer24 {
    /**
     * 剑指 Offer 24. 反转链表
     * 定义一个函数，输入一个链表的头节点，反转该链表并输出反转后链表的头节点。
     * <p>
     * <p>
     * <p>
     * 示例:
     * <p>
     * 输入: 1->2->3->4->5->NULL
     * 输出: 5->4->3->2->1->NULL
     * <p>
     * <p>
     * 限制：
     * <p>
     * 0 <= 节点个数 <= 5000
     */

    public static ListNode reverseList(ListNode head) {

        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }

        return pre;
    }


    public static ListNode reverseListByk(ListNode head, int k) {

        ListNode pre = null;
        ListNode cur = head;
        int count = 0;
        ListNode tmp = null;
        while (cur != null && count < k) {
            tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
            count++;
        }
        head.next = tmp;

        return pre;
    }

    public static void print(ListNode listNode) {

        while (listNode != null) {
            System.out.print(listNode.val);
            listNode = listNode.next;

        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode head2 = new ListNode(2);
        ListNode head3 = new ListNode(3);
        ListNode head4 = new ListNode(4);
        ListNode head5 = new ListNode(5);
        head.next = head2;
        head2.next = head3;
        head3.next = head4;
        head4.next = head5;
        // print(reverseList(head));
        print(reverseListByk(head, 6));

    }
}
